//
//  String+QZSwiftUI.swift
//  CrseAsst
//
//  Created by 申铭 on 2024/3/4.
//

import Foundation

extension String {
    /// 获取字符串首字母
    /// 例："申铭" -> "S"
    /// - Returns: String
    public func getPinyinInitial() -> String {
        let pinyin = self.transformToPinyinWithoutBlank().capitalized
        if pinyin.count > 0 {
            return String(pinyin.prefix(1))
        }
        return ""
    }
    
    /// 字符串转拼音，无空格
    ///  例："申铭" -> "ShenMing"
    /// - Returns: String
    public func transformToPinyinWithoutBlank() -> String {
        let pinyin = self.transformToPinyin()
        return pinyin.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
    }
    
    /// 字符串转拼音
    /// 例："申铭" -> "Shen Ming"
    /// - Returns: String
    public func transformToPinyin() -> String {
        let mutableString = NSMutableString(string: self)
        CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
        CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
        let string = String(mutableString)
        return string
    }
}
